package com.koudai.finance.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.koudai.finance.constant.SysCode;
import com.koudai.finance.dao.SysConfigDao;
import com.koudai.finance.dao.UserDao;
import com.koudai.finance.entity.SysConfig;
import com.koudai.finance.entity.User;
import com.koudai.finance.enums.ResultCode;
import com.koudai.finance.exception.BusinessException;
import com.koudai.finance.service.CommonService;
import com.koudai.finance.utils.NumberUtils;
import com.koudai.finance.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @Description: 商机信息Service
 * @author: ls
 * @Date: 2020-07-14 15:55:36
 */
@Slf4j
@Service
public class CommonServiceImpl implements CommonService {

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private SysConfigDao sysConfigDao;

    @Resource
    private UserDao userDao;

    /**
     * @Description: 构建查询方法的公共返回结果
     * @Author: ls
     * @Date: 2020/08/13 11:09
     */
    @Override
    public <T> Map<String, Object> buildQryResultMap(List<T> beanList) {
        Map<String, Object> resultMap = Maps.newHashMapWithExpectedSize(2);
        PageInfo<T> pageInfo = PageInfo.of(beanList);
        resultMap.put("list", beanList);
        resultMap.put("totalNum", pageInfo.getTotal());
        return resultMap;
    }

    /**
     * @Description: 分页
     * @Author: ls
     * @Date: 2020/08/03 0:30
     */
    @Override
    public <T> List<T> getPageList(List<T> dataList, Integer pageNum, Integer pageSize) {
        List<T> currentPageList = Lists.newArrayList();
        if (dataList != null && dataList.size() > 0) {
            int currIdx = (pageNum != null && pageNum > 1) ? (pageNum - 1) * pageSize : 0;
            for (int i = 0; i < pageSize && i < dataList.size() - currIdx; i++) {
                T data = dataList.get(currIdx + i);
                currentPageList.add(data);
            }
        }
        return currentPageList;
    }

    /**
     * @Description:  获取系统配置列表
     * @Author: ls
     * @Date: 2020/09/03 18:45
     */
    @Override
    public List<SysConfig> getSysConfigList(String key) {
        String redisKey = SysCode.REDIS_KEY_SYS_CONFIG;
        String userStr = redisUtil.get(redisKey);
        if (StringUtils.isNotBlank(userStr)) {
            return JSON.parseArray(userStr, SysConfig.class);
        }
        List<SysConfig> configList = sysConfigDao.getSysConfigList();
        redisUtil.set(redisKey, JSON.toJSONString(configList));
        return configList.stream().filter(obj -> obj.getKey().equals(key)).collect(Collectors.toList());
    }

    /**
     * @Description: 删除用户缓存信息
     * @author: ls
     * @Date: 2020/7/21 20:34
     */
    public void delUserCache(Integer userId) {
        String redisKey = String.format("%s%s", SysCode.REDIS_KEY_USER_INFO, userId);
        redisUtil.del(redisKey);
    }

    /**
     * @Description: 校验短信验证码
     * @Author: ls
     * @Date: 2020/08/03 0:30
     */
    @Override
    public void checkSmsCode(String phone, String smsCode) {
        String key = String.format("%s%s", SysCode.REDIS_KEY_SMS_CODE, phone);
        String redisSmsCode = redisUtil.get(key);
        if (!StringUtils.equals(redisSmsCode, smsCode)) {
            throw new BusinessException(ResultCode.VALIDATE_SMS_CODE_ERROR);
        }
    }

    /**
     * @Description: 获取用户信息
     * @author: ls
     * @Date: 2020/7/21 20:34
     */
    @Override
    public User getUserInfo(Integer userId) {
        String redisKey = String.format("%s%s", SysCode.REDIS_KEY_USER_INFO, userId);
        String userStr = redisUtil.get(redisKey);
        if (StringUtils.isNotBlank(userStr)) {
            return JSON.parseObject(userStr, User.class);
        }
        User user = userDao.getUserById(userId);
        if (user == null) {
            throw new BusinessException(ResultCode.USER_NOT_LOGGED_IN);
        }
        if (StringUtils.isBlank(user.getHeadImgUrl())) {
            user.setHeadImgUrl("https://oss.tengyunhhr.com/other/head.png");
        }
        int random = NumberUtils.getRandom(1, 7);
        redisUtil.set(redisKey, JSON.toJSONString(user), random, TimeUnit.DAYS);
        return user;
    }

}